package com.example.demo7

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.ContentUris
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.Build
import android.os.IBinder
import android.provider.MediaStore
import androidx.core.app.NotificationCompat

class MusicService : Service() {
    
    private var mediaPlayer: MediaPlayer? = null
    private val binder = MusicBinder()
    private var musicList = mutableListOf<Music>()
    private var currentPosition = 0
    private var isPlaying = false
    
    companion object {
        private const val CHANNEL_ID = "MusicPlayerChannel"
        private const val NOTIFICATION_ID = 1
    }
    
    inner class MusicBinder : Binder() {
        fun getService(): MusicService = this@MusicService
    }
    
    override fun onCreate() {
        super.onCreate()
        createNotificationChannel()
        scanMediaFiles()
        
        // 延迟加载音乐列表，给媒体扫描一些时间
        android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
            loadMusicList()
        }, 2000) // 2秒延迟
    }
    
    // 触发媒体扫描
    private fun scanMediaFiles() {
        try {
            val downloadDir = android.os.Environment.getExternalStoragePublicDirectory(
                android.os.Environment.DIRECTORY_DOWNLOADS
            )
            
            if (downloadDir.exists()) {
                android.util.Log.d("MusicService", "Scanning directory: ${downloadDir.absolutePath}")
                
                val audioFiles = mutableListOf<String>()
                downloadDir.listFiles()?.forEach { file ->
                    if (file.isFile && file.extension.lowercase() in listOf("mp3", "m4a", "wav", "flac", "ogg")) {
                        android.util.Log.d("MusicService", "Found audio file: ${file.name}")
                        audioFiles.add(file.absolutePath)
                    }
                }
                
                // 批量扫描所有音频文件
                if (audioFiles.isNotEmpty()) {
                    android.media.MediaScannerConnection.scanFile(
                        this,
                        audioFiles.toTypedArray(),
                        null
                    ) { path, uri ->
                        android.util.Log.d("MusicService", "Scanned: $path -> $uri")
                    }
                    android.util.Log.d("MusicService", "Triggered scan for ${audioFiles.size} files")
                }
            } else {
                android.util.Log.e("MusicService", "Download directory does not exist")
            }
        } catch (e: Exception) {
            android.util.Log.e("MusicService", "Error scanning media files", e)
        }
    }
    
    override fun onBind(intent: Intent?): IBinder {
        return binder
    }
    
    // 使用ContentResolver加载音乐列表
    private fun loadMusicList() {
        musicList.clear()
        val projection = arrayOf(
            MediaStore.Audio.Media._ID,
            MediaStore.Audio.Media.TITLE,
            MediaStore.Audio.Media.ARTIST,
            MediaStore.Audio.Media.DURATION,
            MediaStore.Audio.Media.DATA
        )
        
        // 更宽松的查询条件：只要是音频文件且时长大于0
        val selection = "${MediaStore.Audio.Media.DURATION} > 0"
        val sortOrder = "${MediaStore.Audio.Media.TITLE} ASC"
        
        try {
            contentResolver.query(
                MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                projection,
                selection,
                null,
                sortOrder
            )?.use { cursor ->
                val idColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media._ID)
                val titleColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE)
                val artistColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST)
                val durationColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION)
                val dataColumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA)
                
                android.util.Log.d("MusicService", "Found ${cursor.count} audio files in MediaStore")
                
                while (cursor.moveToNext()) {
                    val id = cursor.getLong(idColumn)
                    val title = cursor.getString(titleColumn) ?: "Unknown"
                    val artist = cursor.getString(artistColumn) ?: "Unknown Artist"
                    val duration = cursor.getLong(durationColumn)
                    val data = cursor.getString(dataColumn) ?: ""
                    
                    android.util.Log.d("MusicService", "Found music: $title - $artist")
                    musicList.add(Music(id, title, artist, duration, data))
                }
            }
            
            android.util.Log.d("MusicService", "Total music loaded from MediaStore: ${musicList.size}")
            
            // 如果MediaStore没有找到音乐，尝试直接从文件系统加载
            if (musicList.isEmpty()) {
                android.util.Log.w("MusicService", "No music in MediaStore, loading from filesystem")
                loadMusicFromFileSystem()
            }
        } catch (e: Exception) {
            android.util.Log.e("MusicService", "Error loading music", e)
        }
    }
    
    // 备选方案：从文件系统直接加载
    private fun loadMusicFromFileSystem() {
        try {
            val downloadDir = android.os.Environment.getExternalStoragePublicDirectory(
                android.os.Environment.DIRECTORY_DOWNLOADS
            )
            
            if (downloadDir.exists()) {
                downloadDir.listFiles()?.forEachIndexed { index, file ->
                    if (file.isFile && file.extension.lowercase() in listOf("mp3", "m4a", "wav", "flac", "ogg")) {
                        val title = file.nameWithoutExtension
                        val music = Music(
                            id = index.toLong(),
                            title = title,
                            artist = "Unknown Artist",
                            duration = 0L, // 无法从文件直接获取时长
                            data = file.absolutePath
                        )
                        musicList.add(music)
                        android.util.Log.d("MusicService", "Loaded from filesystem: ${file.name}")
                    }
                }
                android.util.Log.d("MusicService", "Total music loaded from filesystem: ${musicList.size}")
            }
        } catch (e: Exception) {
            android.util.Log.e("MusicService", "Error loading from filesystem", e)
        }
    }
    
    // 创建通知渠道
    private fun createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val name = "Music Player"
            val descriptionText = "Music Player Notifications"
            val importance = NotificationManager.IMPORTANCE_LOW
            val channel = NotificationChannel(CHANNEL_ID, name, importance).apply {
                description = descriptionText
            }
            val notificationManager = getSystemService(NotificationManager::class.java)
            notificationManager.createNotificationChannel(channel)
        }
    }
    
    // 显示通知
    private fun showNotification(songName: String) {
        val intent = Intent(this, MainActivity::class.java)
        val pendingIntent = PendingIntent.getActivity(
            this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        
        val notification = NotificationCompat.Builder(this, CHANNEL_ID)
            .setContentTitle("正在播放")
            .setContentText(songName)
            .setSmallIcon(android.R.drawable.ic_media_play)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_LOW)
            .build()
        
        val notificationManager = getSystemService(NotificationManager::class.java)
        notificationManager.notify(NOTIFICATION_ID, notification)
    }
    
    // 播放音乐
    fun play() {
        if (musicList.isEmpty()) return
        
        try {
            if (mediaPlayer == null) {
                val music = musicList[currentPosition]
                mediaPlayer = MediaPlayer().apply {
                    setDataSource(music.data)
                    prepare()
                    start()
                    
                    // 播放完成后自动播放下一首
                    setOnCompletionListener {
                        next()
                    }
                }
                showNotification(music.title)
            } else {
                mediaPlayer?.start()
            }
            isPlaying = true
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    
    // 暂停
    fun pause() {
        mediaPlayer?.pause()
        isPlaying = false
    }
    
    // 停止
    fun stop() {
        mediaPlayer?.stop()
        mediaPlayer?.release()
        mediaPlayer = null
        isPlaying = false
    }
    
    // 下一首
    fun next() {
        stop()
        if (musicList.isNotEmpty()) {
            currentPosition = (currentPosition + 1) % musicList.size
            play()
        }
    }
    
    // 上一首
    fun previous() {
        stop()
        if (musicList.isNotEmpty()) {
            currentPosition = if (currentPosition - 1 < 0) {
                musicList.size - 1
            } else {
                currentPosition - 1
            }
            play()
        }
    }
    
    // 获取当前播放位置
    fun getCurrentPosition(): Int {
        return mediaPlayer?.currentPosition ?: 0
    }
    
    // 获取歌曲总时长
    fun getDuration(): Int {
        return mediaPlayer?.duration ?: 0
    }
    
    // 跳转到指定位置
    fun seekTo(position: Int) {
        mediaPlayer?.seekTo(position)
    }
    
    // 获取当前歌曲名称
    fun getCurrentSongName(): String {
        return if (musicList.isNotEmpty()) {
            musicList[currentPosition].title
        } else {
            "无歌曲"
        }
    }
    
    // 获取当前播放状态
    fun isPlaying(): Boolean {
        return isPlaying
    }
    
    // 获取音乐列表大小
    fun getMusicListSize(): Int {
        return musicList.size
    }
    
    // 获取当前播放位置索引
    fun getCurrentIndex(): Int {
        return currentPosition
    }
    
    // 重新加载音乐列表
    fun reloadMusicList() {
        scanMediaFiles()
        android.os.Handler(android.os.Looper.getMainLooper()).postDelayed({
            loadMusicList()
        }, 2000) // 2秒延迟，等待扫描完成
    }
    
    override fun onDestroy() {
        super.onDestroy()
        stop()
    }
}
